import 'dart:math';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/net/api/http_api.dart';
import 'package:ls_work/net/response/food/week_choose_data.dart';
import 'package:ls_work/util/ext_utils.dart';
import 'package:ls_work/util/request_url_utils.dart';
import 'package:ls_work/viewmodel/food/week_menu_view_model.dart';

import '../../../config/global_configs.dart';
import '../../../net/post_request.dart';
import '../../../net/response/food/scan_old_data.dart';
import '../../../net/response/food/week_menu_list_data.dart';
import '../../../res/colors.dart';
import '../../../res/gaps.dart';
import '../../../ui/food/new_week/new_choose_week_submit_page.dart';
import '../../../util/image_utils.dart';
import '../../../widgets/select_item_widget.dart';

class NewChooseWeekMenuViewModel extends WeekMenuViewModel {
  final String? siteId;
  final String? time;
  final String? orderModelType;
  final ScanOldData? oldData;
  final String? useType;

  NewChooseWeekMenuViewModel(BuildContext context,
      {this.siteId, this.time, this.orderModelType, this.oldData, this.useType})
      : super(context,
            siteId: siteId,
            time: time,
            orderModelType: orderModelType,
            oldData: oldData,
            useType: useType);

  var timeSelection = 0;
  var dateSelection = 0;
  WeekMenuContent? selectTime;
  GoodsInfo? selectDate;

  @override
  Future<List<WeekMenuContent>> requestListData() async {
    var data = await PostRequest.weekMenu(
        time, siteId, oldData?.selectOldId.toString(), orderModelType);
    if ('0' == data['code'].toString()) {
      if (data['data'] != null) {
        menuData = WeekMenuListData.fromJson(data['data']);
        menuData?.menuJson?.content?.forEach((time) {
          time.ruleCategory?.forEach((rule) {
            rule.goodsInfo?.forEach((date) {
              date.timeSection = time.timeSection;
              date.timeTypeId = time.timeSection.toStringOrNull();
              date.rangeStart = time.rangeStart;
              date.rangeEnd = time.rangeEnd;
              date.weekDate = getDateValue(date.weekDay??0);

              for (var food in (date.goodsList??<GoodsList>[])) {
                food.oldStatus = food.status;
                food.oldNumber = food.number ?? 0;
                if (food.canSelect && food.isTake == 1) {
                  food.canSelect = false;
                }
              }
              if (!time.goodsInfo
                  .map((e) => e.weekDay)
                  .contains(date.weekDay)) {
                var chooseData = WeekChooseData(
                    name: rule.categary ?? "", max: rule.selectNumber);
                chooseData.goodsList = date.goodsList??[];
                date.chooseData.add(chooseData);
                time.goodsInfo.add(date);
              } else {
                for (var item in time.goodsInfo) {
                  if (item.weekDay == date.weekDay) {

                    var chooseData = WeekChooseData(
                        name: rule.categary ?? "", max: rule.selectNumber);
                    chooseData.goodsList = date.goodsList??[];
                    item.chooseData.add(chooseData);
                  }
                }
              }
            });
          });
        });
        return menuData?.menuJson?.content??[];
      } else {
        throw '未获取到周菜单';
      }
    } else {
      throw data['msg'];
    }
  }

  @override
  Widget menuContent() {
    if (selectTime == null&&listItems.isNotEmpty) {
      selectTime = listItems[timeSelection];
      selectDate = selectTime?.showGoodsInfo[dateSelection];
    }
    getSelectItem();

    return Column(
      children: [
        Container(
          height: 10,
        ),
        SelectItemWidget(
          selectTime?.showGoodsInfo ?? [],
          itemBuilder: (context, item, index, selected) {
            var data = item as GoodsInfo;
            var date = getDate(data.weekDay??0);
            var weekFormat = [D];
            var dateFormat = [m, '月', d, '日'];
            return Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                CommonText(date.formatDateStr(format: weekFormat),
                    textColor: selected ? Colors.white : Colors.black),
                CommonText(date.formatDateStr(format: dateFormat),
                    textColor: selected ? Colors.white : Colors.grey[400]!,
                    textSize: 14.5)
              ],
            ).addToContainer(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  color: selected ? Colours.foodSelectColor : Colors.white,
                  borderRadius: 6.borderRadius),
              padding: EdgeInsets.symmetric(horizontal: 22, vertical: 5),
            );
          },
          scrollDirection: Axis.horizontal,
          position: dateSelection,
          separatorBuilder: (context, index) {
            return Container(
              width: 10,
            );
          },
          padding: EdgeInsets.symmetric(horizontal: 16),
          onCallback: (index, data) {
            dateSelection = index;
            selectDate = data;
            notifyListeners();
          },
        ).addToContainer(width: double.infinity, height: 50),
        Container(
          height: 16,
        ),
        Row(
          children: [
            SelectItemWidget(
              listItems,
              position: timeSelection,
              itemBuilder: (context, item, index, selected) {
                return LeftTimeTypeItemWidget(item, selected);
              },
              onCallback: (index, data) {
                timeSelection = index;
                selectTime = data;
                selectDate = selectTime?.showGoodsInfo[dateSelection];
                notifyListeners();
              },
            ).addToContainer(
                width: 70, margin: EdgeInsets.symmetric(horizontal: 16)),
            ListView(
              children: (selectDate?.chooseData ?? []).map((e) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    if (e.goodsList.isNotEmpty) ...[
                      CommonText("${e.name} 选${e.max}"),
                      Container(
                        height: 15,
                      )
                    ],
                    ListView(
                      children: e.goodsList
                          .map((food) => itemMenuContent(e, food))
                          .toList(),
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                    )
                  ],
                );
              }).toList(),
            ).setWeight(3),
            Container(
              width: 16,
            )
          ],
        ).setWeight(1),
        bottomPriceWidget()
      ],
    );
  }

  Widget itemMenuContent(WeekChooseData data, GoodsList food) {
    return Stack(
      children: [
        Stack(
          children: [
            ImageLoad(
              "${HttpApi.imageHead}${food.attachIds}",
              fit: BoxFit.cover,
              width: 90,
              height: 90,
              placeholder: ImageUtils.getImgPath("none"),
              errorImage: ImageUtils.getImgPath("none"),
            ),
            CommonText(food.goodsName).setLocation(left: 100, top: 4),
            CommonText("¥${food.price}", textColor: Colors.red)
                .setLocation(bottom: 4, left: 100),
            if (RequestUrlUtils.code != "xcyg")
              Row(
                children: [
                  if ((food.status ?? 0) == 1)
                    Icon(
                      Icons.check_circle,
                      color: Colours.foodSelectColor,
                      size: 30,
                    )
                ],
              ).setLocation(bottom: 0, right: 0),
            if (RequestUrlUtils.code == "xcyg")
              Row(
                children: [
                  if ((food.number ?? 0) > 0)
                    Icon(
                      Icons.remove_circle_outline,
                      color: Colours.foodSelectColor,
                    ).onTap(() {
                      removeClick(food);
                    }),
                  Container(
                    width: 15,
                  ),
                  if ((food.number ?? 0) > 0) CommonText("${food.number ?? 0}"),
                  Container(
                    width: 15,
                  ),
                  Icon(
                    Icons.add_circle_rounded,
                    color: Colours.foodSelectColor,
                  ).onTap(() {
                    addClick(food, data);
                  })
                ],
              ).setLocation(bottom: 0, right: 0),
          ],
        ).addToContainer(
            width: double.infinity,
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: 10.borderRadius)),
        if (!food.canSelect || food.isTake == 1)
          Container(
            decoration: BoxDecoration(
                color: Colors.grey.withAlpha(90),
                borderRadius: 10.borderRadius),
            width: double.infinity,
          ).setLocation(top: 0, bottom: 0, left: 0, right: 0)
      ],
    ).onTap(() {
      if (RequestUrlUtils.code == "xcyg") {
        addClick(food, data);
        return;
      }
      multiChooseClick(food, data);
      getSelectItem();
      notifyListeners();
    }).addToContainer(
      margin: EdgeInsets.only(bottom: 10),
    );
  }

  void removeClick(GoodsList food) {
    food.number??=0;
    food.number = food.number!-1;
    if (food.number == 0) {
      food.status = 0;
      food.selected = false;
    }
    getSelectItem();
    notifyListeners();
  }

  void addClick(GoodsList food, WeekChooseData data) {
    if (!food.canSelect) {
      showToast(food.canSelectRemark ?? "该餐不可点");
      return;
    }
    if (1 == food.isTake) {
      showToast("该餐已取餐，不可选择");
      return;
    }

    var max = data.max;
    if ((food.status ?? 0) == 0) {
      if (max == 0 || data.selectList.length < (max??0)) {
        food.status = 1;
        food.number = 1;
        food.selected = true;
      } else {
        showToast("${data.name}最多选择${data.max}个菜品");
      }
    } else {
      food.number = (food.number??0)+1;
    }
    getSelectItem();
    notifyListeners();
  }

  void multiChooseClick(GoodsList food, WeekChooseData data) {
    if (!food.canSelect) {
      showToast(food.canSelectRemark ?? "该餐不可点");
      return;
    }
    if (1 == food.isTake) {
      showToast("该餐已取餐，不可选择");
      return;
    }

    var max = data.max;
    if (max == 0) {
      if ((food.status ?? 0) == 0) {
        food.status = 1;
        food.number = 1;
        food.selected = true;
      } else {
        food.status = 0;
        food.number = 0;
        food.selected = false;
      }
    } else if (max == 1) {
      if (food.status == 1) {
        food.status = 0;
        food.number = 0;
        food.selected = false;
      } else {
        for (var item in data.goodsList) {
          item.status = 0;
          item.number = 0;
          food.selected = false;
        }
        food.status = 1;
        food.number = 1;
        food.selected = true;
      }
    } else {
      if (food.status == 0 && data.selectList.length >= (max??0)) {
        showToast("${data.name}最多选择${data.max}个菜品");
      } else {
        if ((food.status ?? 0) == 0) {
          food.status = 1;
          food.number = 1;
          food.selected = true;
        } else {
          food.status = 0;
          food.number = 0;
          food.selected = false;
        }
      }
    }
  }

  var selectedMealList = <GoodsInfo>[];
  var totalPrice = 0.0;
  var oldPrice = 0.0;

  Widget bottomPriceWidget({bool clickShopcar = true}) {
    return Stack(
      children: [
        Image.asset(
          ImageUtils.getImgPath("food/shop_car"),
          width: 40,
          height: 40,
          color:
              selectedMealList.isEmpty ? Colors.black : Colours.foodSelectColor,
        ).onTap(() {
          if (selectedMealList.isEmpty) {
            return;
          }
          if (!clickShopcar) {
            Go().pop();
            return;
          }
          showSelectBottom();
        }).setLocation(top: 0, bottom: 0, left: 16),
        if (selectedMealList.isNotEmpty)
          CommonText("${selectedMealList.length}",
                  textColor: Colors.white, textSize: 14)
              .addToContainer(
                  decoration: BoxDecoration(
                      color: Colors.red, borderRadius: 20.borderRadius),
                  alignment: Alignment.center,
                  constraints: BoxConstraints(minHeight: 20, minWidth: 20))
              .setLocation(left: 44, top: 8),
        (GlobalConfigs.showPayPrice
                ? Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      CommonText("¥", textSize: 16),
                      CommonText(
                          (totalPrice.d-oldPrice.d)
                              .toStringOrNull(),
                          textSize: 20)
                    ],
                  )
                : CommonText(""))
            .setLocation(top: 0, bottom: 0, left: 70),
        TextButton(
          onPressed: () {
            if (!clickShopcar) {
              Go().pop();
              return;
            }
            Go().push(NewChooseWeekSubmitPage(
              menuData: menuData!,
              oldId: oldData!.selectOldId.toString(),
              sitId: siteId!,
              time: time!,
              orderModelType: orderModelType!,
              useType: useType!,
            ));
          },
          child: CommonText('去结算', textColor: Colors.white),
          style: ButtonStyle(
              backgroundColor: WidgetStateProperty.all(
                  selectedMealList.isEmpty
                      ? Colors.grey
                      : Colours.foodSelectColor),
              shape: WidgetStateProperty.all(StadiumBorder()),
              fixedSize: WidgetStateProperty.all(Size(90, 40))),
        )
            .addToContainer(alignment: Alignment.center)
            .setLocation(right: 16, top: 0, bottom: 0)
      ],
    ).addToContainer(width: double.infinity, height: 65, color: Colors.white);
  }

  void getSelectItem() {
    selectedMealList.clear();
    totalPrice = 0.0;
    oldPrice = 0.0;
    for (var item in listItems) {
      for (var date in item.showGoodsInfo ?? <GoodsInfo>[]) {
        for (var type in date.chooseData) {
          for (var food in type.goodsList) {
            if (1 == food.oldStatus) {
              oldPrice += (food.price??0) * (food.oldNumber ?? 0);
            }
          }
          if (type.selectList.isNotEmpty &&
              type.selectList[0].canSelect &&
              1 != type.selectList[0].isTake) {
            if (!selectedMealList.contains(date)) {
              selectedMealList.add(date);
            }


          }
          totalPrice += type.selectPrice;
        }

      }
    }


    selectedMealList.sort((o1, o2) {
      return o1.weekDay!.compareTo(o2.weekDay!);
    });
  }

  void clearSelected() {
    if (selectedMealList.isEmpty) {
      return;
    }
    for (var item in selectedMealList) {
      for (var type in item.chooseData) {
        for (var food in type.selectList) {
          food.status = 0;
          food.number = 0;
        }
        // type.selectList.clear();
      }
      // item.chooseData.clear();
    }
    selectedMealList.clear();
    getSelectItem();
    notifyListeners();
  }

  void showSelectBottom() {
    showModalBottomSheet<void>(
        context: context,
        builder: (context) {
          return bottomContent();
        },
        isScrollControlled: true,
        constraints: selectedMealList.length >= 3
            ? BoxConstraints(
                maxHeight: MediaQuery.of(context).size.height * 0.7)
            : null);
  }

  Widget bottomContent() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          children: [
            CommonText('已选商品').setWeight(1),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Icon(
                  Icons.delete_outline,
                  color: Colors.grey[800],
                  size: 18,
                ),
                CommonText('清空', textSize: 14, textColor: Colors.grey[800]!)
              ],
            ).onTap(() {
              clearSelected();
              notifyListeners();
              Go().pop();
            })
          ],
        ).addToContainer(
            margin: EdgeInsets.symmetric(horizontal: 16, vertical: 16)),
        selectedMealList.length >= 3
            ? ListView.separated(
                padding: EdgeInsets.symmetric(horizontal: 16),
                itemBuilder: (context, index) {
                  var item = selectedMealList[index];
                  return selectMealItem(item);
                },
                separatorBuilder: (context, index) {
                  return Gaps.dividerLine;
                },
                itemCount: selectedMealList.length,
              ).setWeight(1)
            : ListView.separated(
                padding: EdgeInsets.symmetric(horizontal: 16),
                shrinkWrap: true,
                itemBuilder: (context, index) {
                  var item = selectedMealList[index];
                  return selectMealItem(item);
                },
                separatorBuilder: (context, index) {
                  return Gaps.dividerLine;
                },
                physics: NeverScrollableScrollPhysics(),
                itemCount: selectedMealList.length,
              ),
        bottomPriceWidget(clickShopcar: false)
      ],
    );
  }

  Widget selectMealItem(GoodsInfo info) {
    var paidList = <GoodsList>[];
    var selectList = <GoodsList>[];
    var selectPrice = 0.0;
    var paidPrice = 0.0;
    for (var item in info.chooseData) {
      selectList.addAll(item.selectList);
      paidList.addAll(item.paidList);
      selectPrice += item.selectPrice;
      paidPrice += item.paidPrice;
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          height: 8,
        ),
        Row(
          children: [
            CommonText(
                    "${getDateValue(info.weekDay??0)?.toDateStr([
                          'm',
                          '月',
                          'd',
                          '日'
                        ])}  ${info.timeTypeId?.timeTypeStr()}",
                    textSize: 17,
                    textColor: Colors.grey[700]!,
                    fontWeight: FontWeight.bold)
                .setWeight(1),
            CommonText("¥${selectPrice - paidPrice}",
                textSize: 17, textColor: Colors.red),
          ],
        ),
        Container(
          height: 15,
        ),
        CommonText(
            selectList.map((e) => "${e.goodsName}x${e.number}").join("、"),
            textColor: Colors.grey[800]!,
            textSize: 17),
        Container(
          height: 15,
        ),
        if (paidList.isNotEmpty) ...[
          CommonText(
            '已结算',
            textColor: Colors.grey,
          ),
          Container(
            height: 15,
          ),
          ...paidList
              .map((e) => Row(
                    children: [
                      Container(
                        width: 40,
                      ),
                      CommonText(e.goodsName, textColor: Colors.grey)
                          .setWeight(2),
                      CommonText("x${e.oldNumber}",
                              textColor: Colors.grey,
                              textAlign: TextAlign.center)
                          .setWeight(1),
                      CommonText("¥${e.price}",
                              textColor: Colors.grey, textAlign: TextAlign.end)
                          .setWeight(1),
                    ],
                  ))
              .toList(),
          Container(
            height: 15,
          ),
        ]
      ],
    );
  }
}

Widget LeftTimeTypeItemWidget(WeekMenuContent e, bool selected) {
  return Column(
    children: [
      titleImage(e.timeSection.toString(), selected),
      Container(
        height: 8,
      ),
      CommonText(e.timeStr, textColor: Colors.grey[700]!)
    ],
  ).addToContainer(margin: EdgeInsets.only(bottom: 10));
}
